/*
  ajax模块
  obj请求参数
  needloading是否需要loading样式
*/
let app = getApp()
//域名
const URl_HOST = app.host
let axios = (obj, needloading = true) => {
  return new Promise((resolve, rejected) => {
    if (needloading) {
      wx.showLoading()
    }
    let userinfo = wx.getStorageSync('userinfo')
    let header = obj.method === 'POST' ? { 'content-type': 'application/x-www-form-urlencoded' } : {}  //默认为空
    let url = `${URl_HOST}${obj.url}?userid=${userinfo.userid}&token=${userinfo.token}`
    if (userinfo){  
      url = `${URl_HOST}${obj.url}?userid=${userinfo.userid}&token=${userinfo.token}`
    }else{
      url = `${URl_HOST}${obj.url}`
    }
    let method = obj.method || 'GET'              //默认get
    let data = obj.data || ''                     //默认不传数据
    let dataType = obj.dataType || 'json'         //默认json
    let responseType = obj.responseType || 'text' //默认text
    //如果接口地址栏包含市场推广参数 再进行调用
      wx.request({
        header: header,
        url: url,
        method: method,
        data: data,
        dataType: dataType,
        responseType: responseType,
        success: (res) => {
        //   console.log(res)
          if (needloading) {
            wx.hideLoading()
          }
          //正常登陆
          if (res.data.result == 1){
            resolve(res)
          //登陆超时
          }else if (res.data.result == -1){
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
            wx.login({
              success: function (res) {
                console.log(res.code)
                wx.request({
                  url: URl_HOST + '/user/isBinding',
                  data: {
                    code: res.code
                  },
                  success: res=>{
                      if (res.data.isBinding) {
                          wx.setStorageSync('userinfo', {
                              userid: res.data.userid,
                              token: res.data.token
                          })
                      }
                  }
                })
              }
            })
          //其他报错信息 
          }else{
            wx.showToast({
              title: res.data.message,
              icon: 'none'
            })
          }
        },
        fail: (res) => {
          if (needloading) {
            wx.hideLoading()
          }
          rejected(res)
        }
      })      
  })
}

export {
  axios
}